<template>
	<div>
		<Table class="pile-list" ref="tableRef" :content="true" :toolbar="data.toolbar" :query="data.query"
			@get-list="getList">
			<template #content>
				<div v-for="(item, index) in data.list" :key="index" class="item-wrap">
					<div class="head-wrap">
						<div class="left">
							<el-checkbox class="check-box" v-model="item.select" />
							<div class="text">电桩编码: {{ item.equipmentCode || '--' }}</div>
							<div class="text">功率：{{ item.power || '--' }}kW</div>
							<div class="text">
								在线状态：
								<div class="is-online" :class="{ off: !item.isOnline }"></div>
								{{ item.isOnline ? '在线' : '离线' }}
							</div>
							<div class="text">电桩名称：{{ item.equipmentName || '--' }}</div>
						</div>
						<div class="right">
							<div v-if="bntAuth('pileList.paramTranslate')" class="btn"
								@click="clickParamTranslate(item)">
								参数设置
							</div>
							<div v-if="bntAuth('pileList.paramQuery')" class="btn" @click="clickParamQuery(item)">
								版本查询
							</div>
							<div v-if="bntAuth('pileList.edit')" class="btn" @click="clickEdit(item)">
								修改
							</div>
							<div v-if="bntAuth('pileList.restart')" class="btn" @click="clickRestart(item)">
								远程重启
							</div>
							<div v-if="bntAuth('pileList.updata')" class="btn" @click="clickUpdate(item)">
								远程升级
							</div>
							<div v-if="bntAuth('pileList.time')" class="btn btn1" @click="clickTime(item)">
								校时
							</div>
							<div v-if="bntAuth('pileList.price')" class="btn btn1" @click="clickPrice(item)">
								校价
							</div>
							<div v-if="bntAuth('pileList.delete')" class="btn btn2" @click="clickDelete(item)">
								删除
							</div>
							<div v-if="bntAuth('pileList.fastCode')" class="btn" @click="clickCode(item)">
								快捷码
							</div>
						</div>
					</div>
					<div class="info-wrap">
						<div class="left">
							<div class="text">归属电站：{{ item.stationName || '--' }}</div>
							<div class="text">品牌/型号：{{ brandModel(item) }}</div>
							<div class="text">
								固件版本：{{ item.firmwareVersion || '--' }}
							</div>
							<!-- <div class="text">
								最新校价时间：{{ item.lastPriceTime || '--' }}
							</div> -->
							<div class="text">
								版本信息：{{ item.equVersion || '--' }}
							</div>
							<div class="text">
								SIM卡号：{{ item.numberSIM || '--' }}
							</div>
						</div>
						<div class="right">
							<Table ref="tableRef1" :columns="data.columns" :handles="data.handles" :border="true"
								:isPost="false" :isPagination="false" :list="item.pageConnectorDTOS || []"></Table>
						</div>
					</div>
				</div>
				<div v-if="data.list.length === 0" class="no-data-wrap">
					<div class="no-data"></div>
					<div class="text">暂无数据</div>
				</div>
			</template>
		</Table>
		<DialogCode ref="dialogCodeRef" @update-list="updateList"></DialogCode>
		<DialogUpdate ref="dialogUpdateRef"></DialogUpdate>
		<DialogParamQuery ref="dialogParamQuery"></DialogParamQuery>
		<DialogParamTranslate ref="dialogParamTranslate"></DialogParamTranslate>
		<DialogRemoteUpdate ref="dialogRemoteUpdate"></DialogRemoteUpdate>
	</div>
</template>

<script lang="ts" setup name="pileList">
	import Table from '@/components/table/index.vue';
	import DialogCode from '../components/dialogCode.vue';
	import DialogUpdate from '../components/dialogUpdate.vue';
	import DialogParamQuery from '../components/dialogParamQuery.vue';
	import DialogParamTranslate from '../components/dialogParamTranslate.vue';
	import DialogRemoteUpdate from '../components/dialogRemoteUpdate.vue';
	import {
		pageQueryEquipment,
		URL_EQUIPMENTIMPORT,
		startConnector,
		stopConnector,
		equipmentBrandAndModelTreeData,
		getQRCode,
		queryAllEquipmentModelPower,
		batchCheckPrices,
		batchCheckTime,
		delEquipment,
		EXPORT_EQUIPMENT,
		remoteRestart,
		paramQueryBatch,
	} from '@/service/apis/pile';
	import { queryDicByParent } from '@/service/apis/api';
	import { STATION_STATUS_USE, PILE_ONLINE } from '@/utils/dictionaries';
	import { bntAuth, exportFile } from '@/utils/utils';

	const router = useRouter();

	const tableRef = ref();
	const tableRef1 = ref();
	const dialogCodeRef = ref();
	const dialogUpdateRef = ref();
	const dialogParamQuery = ref();
	const dialogParamTranslate = ref();
	const dialogRemoteUpdate = ref();

	const emit = defineEmits(['get-update']);
	onActivated(() => {
		emit('get-update', (flag : boolean) => {
			if (flag) {
				tableRef.value?.getData();
			}
		});
	});

	queryDicByParent({
		listDtos: ['connectorWorkStatus', 'equipmentModelType'],
	}).then((res : any) => {
		if (res) {
			if (import.meta.env.VITE_ENV_TYPE === 'lznt') {
				data.query[6].props.options = [...res.equipmentModelType];
				data.query[9].props.options = [...res.connectorWorkStatus];
			} else {
				data.query[5].props.options = [...res.equipmentModelType];
				data.query[8].props.options = [...res.connectorWorkStatus];
			}
		}
	});

	// 获取电桩功率
	queryAllEquipmentModelPower({}).then((res : any) => {
		if (res) {
			if (import.meta.env.VITE_ENV_TYPE === 'lznt') {
				data.query[7].props.options = [...res];
			} else {
				data.query[6].props.options = [...res];
			}
		}
	});

	//获取品牌型号数据
	equipmentBrandAndModelTreeData({}).then((res : any) => {
		if (res) {
			if (import.meta.env.VITE_ENV_TYPE === 'lznt') {
				data.query[5].props.options = [...res];
			} else {
				data.query[4].props.options = [...res];
			}
		}
	});

	const brandModel = (item : any) => {
		if (item.equipmentBrandName && item.equipmentModelName) {
			return `${item.equipmentBrandName}/${item.equipmentModelName}`;
		}
		return '--';
	};

	const data = reactive({
		list: [] as any,
		toolbar: [
			{
				label: '新增',
				permission: 'pileList.add',
				icon: 'icon-add',
				type: 'primary',
				handle: (row : any) => {
					router.push({
						name: 'pileAdd',
					});
				},
			},
			{
				label: '批量新增',
				permission: 'pileList.add',
				icon: 'icon-add',
				type: 'primary',
				handle: (row : any) => {
					router.push({
						name: 'pileBatchAdd',
					});
				},
			},
			{
				label: '模板下载',
				permission: 'pileList.import',
				icon: 'icon-download',
				type: 'primary',
				plain: true,
				url: '%E5%85%85%E7%94%B5%E6%A1%A9%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx',
			},
			{
				label: '导入',
				permission: 'pileList.import',
				icon: 'icon-import',
				type: 'primary',
				plain: true,
				import: true,
				url: URL_EQUIPMENTIMPORT,
			},
			{
				label: '导出二维码',
				permission: 'pileList.code',
				type: 'primary',
				plain: true,
				handle: (row : any) => {
					// console.log('导出---', data.list)
					// let arr = [] as any;
					// data.list.forEach((item: any) => {
					//   if (item.select) {
					//     arr.push(item.id);
					//   }
					// });
					// if (arr.length === 0) {
					//   ElMessageBox.alert('请勾选需要导出二维码的电桩', '提示', {
					//     confirmButtonText: '确认',
					//     type: 'warning',
					//   });
					//   return;
					// }
					// getQRCode({ equipmentIds: arr });
					getQRCode(tableRef.value?.getForm());
				},
			},
			{
				label: '批量校价',
				permission: 'pileList.batchPrice',
				type: 'primary',
				plain: true,
				handle: (row : any) => {
					console.log('批量校价---', row);
					let arr = [] as any;
					data.list.forEach((item : any) => {
						if (item.select) {
							arr.push(item.id);
						}
					});
					if (arr.length === 0) {
						ElMessage({
							showClose: true,
							message: '请勾选需要批量校价的电桩',
							type: 'warning',
						});
						return;
					}
					batchCheckPrices({ ids: arr }).then((res : any) => {
						console.log('res---', res);
						const timer = setTimeout(() => {
							tableRef.value.getData();
							clearTimeout(timer);
						}, 1000);
						ElMessage({
							showClose: true,
							message: '批量校价成功！',
							type: 'success',
						});
					});
				},
			},
			{
				label: '批量校时',
				permission: 'pileList.batchTime',
				type: 'primary',
				plain: true,
				handle: (row : any) => {
					console.log('批量校时---', row);
					let arr = [] as any;
					data.list.forEach((item : any) => {
						if (item.select) {
							arr.push(item.id);
						}
					});
					if (arr.length === 0) {
						ElMessage({
							showClose: true,
							message: '请勾选需要批量校时的电桩',
							type: 'warning',
						});
						return;
					}
					batchCheckTime({ ids: arr }).then((res : any) => {
						console.log('res---', res);
						ElMessage({
							showClose: true,
							message: '批量校时成功！',
							type: 'success',
						});
					});
				},
			},
			{
				label: '导出',
				permission: 'pileList.export',
				icon: 'icon-export',
				type: 'primary',
				plain: true,
				handle: (row : any) => {
					console.log('导出---', row);
					exportFile(EXPORT_EQUIPMENT, '电桩列表', tableRef.value?.getForm());
				},
			},
			{
				label: '批量更新',
				permission: '',
				icon: '',
				type: 'primary',
				plain: true,
				handle: (row : any) => {
					clickRemoteUpdate(row);
				},
			},
			{
				label: '更新版本查询',
				permission: '',
				icon: '',
				type: 'primary',
				plain: true,
				handle: (row : any) => {
					paramQueryBatch({}).then((res : any) => {
						if (res) {
							// console.log('更新版本查询---',res);
							tableRef.value.getData();
						}
					});
				},
			},
		],
		query: [
			{
				label: '终端名称',
				prop: 'equipmentName',
				comName: 'input',
				props: {
					placeholder: '请输入终端名称',
				},
			},
			{
				label: '归属电站',
				prop: 'stationName',
				comName: 'input',
				props: {
					placeholder: '请输入归属电站',
				},
			},
			{
				label: '终端编码',
				prop: 'connectorCode',
				comName: 'input',
				props: {
					placeholder: '请输入终端编码',
				},
			},
			{
				label: '电桩编码',
				prop: 'equipmentCode',
				comName: 'input',
				props: {
					placeholder: '请输入电桩编码',
				},
			},
			{
				label: '电桩品牌/型号',
				prop: 'brandModel',
				comName: 'cascader',
				props: {
					placeholder: '请选择电桩品牌/型号',
					props: {
						checkStrictly: true,
					},
					options: [] as any,
				},
			},
			{
				label: '电桩类型',
				prop: 'type',
				comName: 'select',
				props: {
					placeholder: '请选择电桩类型',
					options: [] as any,
				},
			},
			{
				label: '电桩功率',
				prop: 'power',
				comName: 'select',
				props: {
					placeholder: '请选择电桩功率',
					options: [] as any,
				},
			},
			{
				label: '启停状态',
				prop: 'isEnableStart',
				comName: 'select',
				props: {
					placeholder: '请选择启停状态',
					options: STATION_STATUS_USE,
				},
			},
			{
				label: '工作状态',
				prop: 'workStatus',
				comName: 'select',
				props: {
					placeholder: '请选择工作状态',
					options: [] as any,
				},
			},
			{
				label: '在线状态',
				prop: 'isOnline',
				comName: 'select',
				props: {
					placeholder: '请选择在线状态',
					options: PILE_ONLINE,
				},
			},
			{
				label: '功率版本',
				prop: 'beginEquVersion',
				comName: 'input',
				props: {
					placeholder: '≥输入值',
				},
			},
			{
				label: '功率版本',
				prop: 'endEquVersion',
				comName: 'input',
				props: {
					placeholder: '≤输入值',
				},
			},
			// {
			// 	label: '平台运营商',
			// 	prop: 'channelName',
			// 	comName: 'input',
			// 	props: {
			// 		placeholder: '请输入平台运营商',
			// 	},
			// },
		],
		columns: [
			{
				prop: 'connectorName',
				label: '终端名称',
			},
			{
				prop: 'connectorCode',
				label: '终端编码',
			},
			{
				prop: 'isEnableStart',
				label: '启停状态',
				template: (row : any) => {
					return row.isEnableStart
						? `<div><div class="is-online on1"></div>启用</div>`
						: `<div><div class="is-online off1"></div>停用</div>`;
				},
			},
			{
				prop: 'workStatusName',
				label: '工作状态',
			},
		],
		handles: [
			{
				label: '启用',
				permission: 'pileList.use',
				labelFun: (row : any) => {
					return !row.isEnableStart ? '启用' : '停用';
				},
				colorFun: (row : any) => {
					return !row.isEnableStart ? '#01C68B' : '#FA3939';
				},
				handle: (row : any) => {
					const msg = !row.isEnableStart
						? '是否启用该终端？'
						: '用终端停用后不可使用，是否继续？';
					ElMessageBox.confirm(msg, '提示', {
						confirmButtonText: '确认',
						cancelButtonText: '取消',
						type: 'warning',
					}).then(() => {
						if (row.isEnableStart) {
							stopConnector({
								id: row.id,
							}).then((res : any) => {
								if (res) {
									row.isEnableStart = !row.isEnableStart;
								}
							});
						} else {
							startConnector({
								id: row.id,
							}).then((res : any) => {
								if (res) {
									row.isEnableStart = !row.isEnableStart;
								}
							});
						}
					});
				},
			},
			{
				label: '详情',
				handle: (row : any) => {
					console.log('详情---', row);
					if (row.workStatus == 3) {
						let routeData = router.resolve({
							path: '/realTimeOrderDetail',
							query: {
								id: row.orderId
							}
						})
						window.open(routeData.href, '_blank');
					} else {
						router.push({
							name: 'pileDetail',
							query: { id: row.id },
						})
					}
				},
			},
		],
	});

	if (import.meta.env.VITE_ENV_TYPE === 'lznt') {
		data.query.splice(0, 0, {
			label: '快捷码',
			prop: 'shortcutCode',
			comName: 'input',
			props: {
				placeholder: '请输入快捷码',
			},
		});
		data.columns.splice(2, 0, {
			prop: 'shortcutCode',
			label: '快捷码',
		});
	}

	const getList = (page : any, search : any) => {
		const form = search.ruleForm;
		delete form.equipmentBrand;
		delete form.equipmentModel;
		if (form.brandModel?.length === 1) {
			form.equipmentBrand = form.brandModel[0];
		}
		if (form.brandModel?.length === 2) {
			form.equipmentBrand = form.brandModel[0];
			form.equipmentModel = form.brandModel[1];
		}
		pageQueryEquipment(form, page).then((res : any) => {
			console.log('res---', res.dataList);
			if (page.pageNo !== 1 && (!res.dataList || res.dataList?.length === 0)) {
				page.pageNo--;
				getList(page, search);
				return;
			}
			const arr = res.dataList || [];
			data.list = [...arr];
			data.list.map((item : any) => (item.select = false));
			tableRef.value?.setTable({
				total: res.totalCount,
				table: data.list,
			});
		});
	};

	const clickEdit = (row : any) => {
		router.push({
			name: 'pileEdit',
			query: { id: row.id },
		});
	};
	const clickTime = (row : any) => {
		batchCheckTime({ id: row.id }).then((res : any) => {
			console.log('res---', res);
			ElMessage({
				showClose: true,
				message: '校时成功！',
				type: 'success',
			});
		});
	};
	const clickPrice = (row : any) => {
		batchCheckPrices({ id: row.id }).then((res : any) => {
			console.log('res---', res);
			ElMessage({
				showClose: true,
				message: '校价成功！',
				type: 'success',
			});
			const timer = setTimeout(() => {
				tableRef.value.getData();
				clearTimeout(timer);
			}, 1000);
		});
	};
	const clickDelete = (row : any) => {
		ElMessageBox.confirm(
			'确认删除该电桩？删除电桩会将电桩下所有终端一同删除',
			'提示',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			delEquipment({ id: row.id }).then((res : any) => {
				tableRef.value.getData();
			});
		});
	};
	const clickCode = (row : any) => {
		dialogCodeRef.value?.show(row);
	};

	const clickRestart = (row : any) => {
		remoteRestart({ id: row.id }).then((res : any) => {
			console.log('res---', res);
			ElMessage({
				showClose: true,
				message: '远程重启指令下发成功，请稍后查看电桩状态！',
				type: 'success',
			});
		});
	};
	const clickParamTranslate = (row : any) => {
		dialogParamTranslate.value?.show(row);
	};
	const clickParamQuery = (row : any) => {
		dialogParamQuery.value?.show(row);
	};
	const clickUpdate = (row : any) => {
		dialogUpdateRef.value?.show(row);
	};
	const updateList = () => {
		tableRef.value.getData();
	};
	const clickRemoteUpdate = (row : any) => {
		dialogRemoteUpdate.value?.show(row);
	};
</script>

<style lang="scss" scoped>
	.pile-list {
		.item-wrap {
			margin-top: 16px;
			border: 1px solid #c4c4c4;
			border-radius: 12px;

			&:first-child {
				margin-top: 0;
			}

			.head-wrap {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 20px;
				height: 50px;
				background-color: #f6f8ff;
				font-size: 13px;
				color: #242424;
				border-top-left-radius: 12px;
				border-top-right-radius: 12px;

				.left {
					display: flex;
					align-items: center;

					.check-box {
						margin-right: 10px;
					}

					.text {
						padding-right: 48px;
					}
				}

				.right {
					display: flex;
					align-items: center;

					.btn {
						padding-left: 12px;
						color: var(--el-color-primary);
						cursor: pointer;
					}

					.btn1 {
						color: #01c68b;
					}

					.btn2 {
						color: #fa3939;
					}
				}
			}

			.info-wrap {
				display: flex;
				justify-content: space-between;
				padding: 14px 20px;
				font-size: 12px;

				.left {
					display: flex;
					flex-direction: column;
					width: 35%;

					.text {
						padding: 6px 0;
					}
				}

				.right {
					width: 75%;
				}
			}

			:deep(.is-online) {
				display: inline-block;
				width: 8px;
				height: 8px;
				margin-right: 2px;
				border-radius: 50%;
				background-color: #01c68b;
			}

			.off {
				background-color: #fa3939;
			}

			:deep(.off1) {
				margin-right: 6px;
				background-color: #fa3939;
			}

			:deep(.on1) {
				margin-right: 6px;
			}
		}

		:deep(.el-table) {
			--el-table-border-color: #e8e8e8;
			border-radius: 0;
		}
	}
</style>